﻿using Meta.Vlc;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VideoCarousel.Control;
using VideoCarousel.Entity;
using VideoCarousel.Tool;
using static Microsoft.WindowsAPICodePack.Shell.PropertySystem.SystemProperties.System;
using Task = System.Threading.Tasks.Task;


namespace VideoCarousel
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class NetPlay : Window, IPlayCtr
    {
        private System.Windows.Threading.DispatcherTimer DispatcherTimer;
      
        public NetPlay()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
            this.Closing += MainWindow_Closing;
            media.LoadedBehavior = MediaState.Manual;
            media.UnloadedBehavior = MediaState.Manual;
            CarouselInit();
        }
        private bool isClose = false;
        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            isClose = true;
            media.Close();
            if (DispatcherTimer != null)
                DispatcherTimer.Stop();
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {

            media.MediaEnded += Media_MediaEnded;
           
          
            bool isFullScreen = Convert.ToBoolean(VCLib.Util.ConfigHelp.ReadConfig("isFullScreen"));
            if (isFullScreen)
            {
                this.WindowStyle = WindowStyle.None;
                this.ResizeMode = ResizeMode.NoResize;
                this.Left = VCLib.Util.ConfigHelp.ReadConfig<double>("left");
                this.Top = VCLib.Util.ConfigHelp.ReadConfig<double>("top");
                this.Width = VCLib.Util.ConfigHelp.ReadConfig<double>("width");
                this.Height = VCLib.Util.ConfigHelp.ReadConfig<double>("height");
                this.Topmost = true;
            }
   
            DispatcherTimer = new System.Windows.Threading.DispatcherTimer(
                new TimeSpan(0, 0, 0, 10, 0),
                System.Windows.Threading.DispatcherPriority.Normal,
                Timer_Elapsed,
                this.Dispatcher);
            DispatcherTimer.Start();
            this.MouseMove += MainWindow_MouseMove; 


            AppControl.Instance.rootPath = rootTemp;
            AppControl.Instance.PlayCtr = this;
            AppControl.Instance.Init();
            this.DataContext = AppControl.Instance;
            SetVolume(AppControl.Instance.PlayStateInfo.Vol);
            Full(AppControl.Instance.PlayStateInfo.IsFull);
        }

        private void Media_MediaEnded(object sender, RoutedEventArgs e)
        {
            if (AppControl.Instance.PlayStateInfo.PlayType== 1)
            {
                Task.Run(() => {
                    media.Dispatcher.Invoke(() => {
                        if (AppControl.Instance.PlayStateInfo != null)
                        {
                            media.Stop();
                            media.Source = new Uri(AppControl.Instance.PlayStateInfo.FullName);
                            media.Play();
                        }
                       
                    });
                });
            }
            else if(AppControl.Instance.PlayStateInfo.PlayType == 2)
            {
                Task.Run(() => {
                    AppControl.Instance.NextPlay();
                });

            }
            else if (AppControl.Instance.PlayStateInfo.PlayType == 3)
            {
                Task.Run(() => {
                    AppControl.Instance.RandowPlay();
                });

            }
            else
            {
                AppControl.Instance.PlayStateInfo.PlayState = 0;
            }
        }

       

        private void NotCarouselSelect_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.Filter = "视频|*.mp4;*.mov;*.mp4;*.avi;*.rmvb;*.flv;*.3gp;*.mpeg;*.mpg4;*.wmva;";
            if(openFileDialog.ShowDialog()== true)
            {
                media.Stop();
                media.Source=new Uri(openFileDialog.FileName);
                media.Play();
            }
        }
        private string rootTemp = null;
        private void CarouselInit()
        {


            MenuItem updateFolder = new MenuItem() { Header = "更换视频文件夹" };
            updateFolder.Click += UpdateFolder_Click;
            contextMenu.Items.Insert(0, updateFolder);

            string folder = VCLib.Util.ConfigHelp.ReadConfig("videoFolder");
        check2:

            if (System.IO.Directory.Exists(folder))
            {
                rootTemp = folder;
            }
            else
            {
                var msgRes = MessageBox.Show("视频文件夹不存在，是否重新选择路径", "提示", MessageBoxButton.YesNo);
                if (msgRes == MessageBoxResult.Yes)
                {
                    folder = OpenFolder();
                    if (folder == null)
                    {
                        this.Close();
                        return;
                    }
                    VCLib.Util.ConfigHelp.SaveConfig("videoFolder", folder);

                    goto check2;
                }
                else
                {
                    this.Close();
                    return;
                }
            }

        }


        private void UpdateFolder_Click(object sender, RoutedEventArgs e)
        {
            string folder = OpenFolder();
            if (folder!=null)
            {
                VCLib.Util.ConfigHelp.SaveConfig("videoFolder", folder);
                MessageBox.Show("保存成功，重启生效");
            }
        }

        Point mp;
        private bool? mouseIsShow;
        private void Timer_Elapsed(object sender, EventArgs e)
        {
            var c = Mouse.GetPosition(this);
            if (c.X == mp.X && c.Y == mp.Y)
            {
                mp.X = c.X;
                mp.Y = c.Y;
                if (mouseIsShow == false)
                    return;
                Mouse.OverrideCursor = Cursors.None;
                mouseIsShow = false;
            }
            else
            {
                mp.X = c.X;
                mp.Y = c.Y;
                if (mouseIsShow == true)
                    return;
                Mouse.OverrideCursor = Cursors.Arrow;
                mouseIsShow = true;
            }
        }
        private void MainWindow_MouseMove(object sender, MouseEventArgs e)
        {
            if (Mouse.OverrideCursor == Cursors.None)
            {
                mouseIsShow = true;
                Mouse.OverrideCursor = Cursors.Arrow;
            }
        }
    

        private string OpenFolder()
        {
            Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog openFileDialog = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            openFileDialog.IsFolderPicker = true;
            openFileDialog.Multiselect = true;
            if (openFileDialog.ShowDialog() == Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult.Ok)
            {
                return openFileDialog.FileName;
            }
            return null;

        }
        
        private void _vlc_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (AppControl.Instance.PlayStateInfo.PlayState==2)
            {
                Play();
            }
            else
            {
                Pause();
            }
        }

       
        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

       

        private void Set_Click(object sender, RoutedEventArgs e)
        {
            var topmost = this.Topmost;
            if (topmost)
                this.Topmost = false;
            SetWindow.Set();
            if (topmost)
                this.Topmost = true;

        }
        public void Play()
        {
            media.Dispatcher.Invoke(new Action(() =>
            {
                if (AppControl.Instance.PlayStateInfo.FullName != null)
                {
                    if(AppControl.Instance.PlayStateInfo.PlayState==0)
                        media.Source = new Uri(AppControl.Instance.PlayStateInfo.FullName);
                    AppControl.Instance.PlayStateInfo.PlayState = 1;
                    media.Play();
                }
            }));
        }
        public void Play(string fileName)
        {
            media.Dispatcher.Invoke(new Action(() =>
            {
                if (!System.IO.File.Exists(fileName))
                    throw new Exception("文件不存在");
                media.Source = new Uri(fileName);
                media.Play();
                AppControl.Instance.PlayFileNameUpdate(fileName);

            }));
        }

        public void Stop()
        {
            media.Dispatcher.Invoke(new Action(() =>
            {
             
                media.Stop();
                AppControl.Instance.PlayStateInfo.PlayState = 0;

            }));
        }

        public void Pause()
        {
            media.Dispatcher.Invoke(new Action(() =>
            {

                media.Pause();
                AppControl.Instance.PlayStateInfo.PlayState = 2;

            }));
        }

        public void SetVolume(int volume)
        {
            media.Dispatcher.Invoke((Action)(() =>
            {
                var v = volume / 100d;
                media.Volume = v;
            }));
        }
        public void Seek(double seek)
        {
            media.Dispatcher.Invoke((Action)(() =>
            {
                media.Position = TimeSpan.FromSeconds(seek);
            }));
        }

        public void UpdatePlaySate()
        {
            if (isClose) return;
            media.Dispatcher.Invoke((Action)(() => {
                AppControl.Instance.PlayStateInfo.Current = media.Position.TotalSeconds;
                if(media.NaturalDuration.HasTimeSpan)
                    AppControl.Instance.PlayStateInfo.Count = media.NaturalDuration.TimeSpan.TotalSeconds;
                AppControl.Instance.PlayStateInfo.Vol = (int)(media.Volume*100);
                AppControl.Instance.PlayStateInfo.IsFull = media.Stretch == Stretch.Fill ? 1 : 0;
            }));
         
       
        }

        public void Full(int isFull)
        {
            media.Dispatcher.Invoke(() => {
                if(isFull==1) 
                    media.Stretch = Stretch.Fill;
                else
                    media.Stretch = Stretch.Uniform;
            });
        }
    }
}
